<?php

namespace app\admin\controller;

use app\admin\business\OrdersBus;
use app\admin\model\Config as ConfigModel;
use app\admin\model\Goods as goodsModel;
use app\admin\model\OrdersGoods;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\Where;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Orders extends Common
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 订单列表
     * @author lijia
     * @date 2019-08-08
     */
    public function index()
    {
        if (Request::isPost()) {
            $key = input('post.key');
            $status = input('post.status',0,'intval');
            $start_time = input('post.start_time');
            $end_time = input('post.end_time');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $sort_by = input('sort_by') ? input('sort_by') : 'id';
            $sort_order = input('sort_order') ? input('sort_order') : 'desc';
            $where = [];
            if ($key) {
                $where[] = ['a.order_sn|b.realname|b.mobile|b.username', 'like', "%" . $key . "%"];
            }
            if ($start_time){
                $where[] = ['a.create_time','>',$start_time];
            }
            if ($end_time){
                $where[] = ['a.create_time','<',$end_time];
            }
            if ($status) {
                $where[] = ['a.status', '=', $status];
            }
            $list = OrdersBus::getList($where,$sort_by,$sort_order,$pageSize,$page);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        return View::fetch();
    }


    /**
     * 导出待发货订单
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function exportExcel(){
        $where = ['a.status' => 1];
        $list = Db::name('orders')->alias('a')
            ->join('user b','b.user_id = a.user_id','left')
            ->join('address c','c.id = a.address_id','left')
            ->where($where)
            ->field('a.*,b.shop_name,c.name,c.address,c.mobile')
            ->select()->toArray();
        foreach ($list as $k => $v){
            $goods = Db::name('orders_goods')->alias('a')
                ->join('goods b','a.goods_id = b.id','left')
                ->where('a.order_id',$v['id'])
                ->field('b.title,b.goods_num,a.goods_share_num')
                ->select()->toArray();
            $str = '';
            foreach ($goods as $key => $val){
                $str .= " 商品".($key+1).': '.$val['goods_num']."-".$val['title']."-份数：".$val['goods_share_num']."; ";
            }
            $list[$k]['goods'] = $str;
        }
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('待发货订单');
        $worksheet->calculateColumnWidths();
        // 设置列的宽度
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(35);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(70);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(40);
        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '待发货订单列表');
        $worksheet->setCellValueByColumnAndRow(1, 2, '定单编号');
        $worksheet->setCellValueByColumnAndRow(2, 2, '店铺名称');
        $worksheet->setCellValueByColumnAndRow(3, 2, '总价');
        $worksheet->setCellValueByColumnAndRow(4, 2, '商品信息');
        $worksheet->setCellValueByColumnAndRow(5, 2, '收货人');
        $worksheet->setCellValueByColumnAndRow(6, 2, '收货电话');
        $worksheet->setCellValueByColumnAndRow(7, 2, '收货地址');
        $worksheet->setCellValueByColumnAndRow(8, 2, '备注');
        $worksheet->setCellValueByColumnAndRow(9, 2, '下单时间');
        //合并单元格
        $worksheet->mergeCells('A1:I1');
        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //设置单元格样式
        $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(14);
        $worksheet->getStyle('A2:I2')->applyFromArray($styleArray)->getFont()->setSize(10);
        $len = count($list);
        for ($i=0; $i < $len; $i++) {
            $j = $i + 3; //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['order_sn']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['shop_name']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $list[$i]['total_price']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['goods']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['name']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['mobile']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['address']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $list[$i]['remarks']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $list[$i]['create_time']);
        }
        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_jzInfo = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:I'.$total_jzInfo)->applyFromArray($styleArrayBody);
        $filename = '待发货订单列表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 查看
     */
    public function detail()
    {
        try {
            $id = input('id', 0, 'intval');
            if (!$id) {
                return ['code' => 1, 'msg' => '非法请求!'];
            }
            $info = Db::name('orders')->alias('a')
                ->join('user b','b.user_id = a.user_id','left')
                ->where('a.id',$id)
                ->field('a.*,b.username,b.mobile')
                ->find();
            $goods = Db::name('orders_goods')->alias('a')
                ->join('goods b', 'b.id = a.goods_id', 'left')
                ->where('a.orders_id', $id)
                ->field('a.goods_id,a.num,a.deposit_price,b.title,b.cover,b.store_name')
                ->select()->toArray();
            $title = '';
            foreach ($goods as $key => $val) {
                $title .= $val['title'] .'*'. $val['num'].'; ';
            }
            $info['goods'] = $title;
            $this->assign('info', $info);
            return View::fetch();
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 编辑
     * @author lijia
     * @date 2019-08-08
     */
    public function edit()
    {
        try {
            if (request()->isPost()) {
                $post = input('post.');
                $where['id'] = $post['id'];
                Db::name('orders')->where($where)->update(['remarks' => $post['remarks']]);
                return ['code' => 0, 'msg' => '操作成功!'];
            } else {
                $id = input('id', 0, 'intval');
                if (!$id) {
                    return ['code' => 1, 'msg' => '非法请求!'];
                }
                $info = Db::name('orders')->find($id);
                $address = Db::name('address')->find($info['address_id']);
                $user = Db::name('user')->where('user_id',$info['user_id'])->field('shop_name,shop_person,mobile')->find();
                $goods = Db::name('orders_goods')->alias('a')
                    ->join('goods b','a.goods_id = b.id','left')
                    ->where('a.order_id',$id)
                    ->field('a.goods_share_num,b.id,b.title,b.cover,b.price,b.share,b.goods_num,b.price')
                    ->select()->toArray();
                $this->assign('info', $info);
                $this->assign('goods', $goods);
                $this->assign('user', $user);
                $this->assign('address', $address);
                $this->assign('info', $info);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 删除
     * @return Array|array
     */
    public function doDelete()
    {
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            $result = Db::name('orders')->where("id", $id)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }



    /**
     * 核销
     * @return Array|array
     */
    public function deliver()
    {
        try {
            $post = input('request.');
            if (!$post['id']) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $data = [
                'receipt_time' => toDate(time()),
                'status' => 4
            ];
            $result = Db::name('orders')->where("id", $post['id'])->update($data);
            if ($result) {
                return ['code' => 0, 'msg' => '核销成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


}